/*
 * io_device.c
 *
 *  Created on: Mar 4, 2012
 *
 */
#ifdef __unix__
# include <unistd.h>
#elif defined _WIN32
# include <windows.h>
#define sleep(x) Sleep(1000 * x)
#endif


#include<stdio.h>
#include<unistd.h>
#include "io_device.h"
#include "../CPU/interrupt.h"
#include "../Utility/queue.h"

int io_device_init(io_device* io_ptr, Queue the_interrupt_q, int the_type)
{
	/* all IO devices... */
	io_ptr->trap = 0;
	io_ptr->my_blocked_q = CreateQueue(10);
	io_ptr->my_interrupt_q = the_interrupt_q;
	io_ptr->my_type = the_type;

	return 0;
}

void run_io(io_device* io_ptr){
	/* AUX IO */
		if (io_ptr->my_type == 0){
			interrupt * intr;
			char *process_name = "Aux I/O Device";
			char * data = process_name;
			int i = 0;
			while(1){
				if (io_ptr->trap){
					sleep(10);
					printf("IO Device Thinking Very Hard About Your Request...\n");
					i++;
					//create interrupt
					interrupt_init(intr, 0, process_name, data, io_ptr->my_blocked_q);
					//process interrupt
					Enqueue(intr, io_ptr->my_interrupt_q);
					io_ptr->trap--;
				}

			}
		/* keyboard */
		}else {
			interrupt * intr;
			char *process_name = "Keyboard";

			while(1){
				//printf("KEYBOARD: Listening for Input\n");

				// Source: http://stackoverflow.com/questions/314401/how-to-read-a-line-from-the-console-in-c
				// Reading Lines from google search...
				char line[1024];  /* Generously large value for most situations */
				char *data;
				line[0] = '\0'; /* Ensure empty line if no input delivered */
				line[sizeof(line)-1] = ~'\0';  /* Ensure no false-null at end of buffer */
				data = fgets(line, sizeof(line), stdin);
				// End Stackoverflow Code

				//printf("KEYBOARD: Read from Console: %s\n", data);
				//create interrupt
				interrupt_init(intr, 0, process_name, data, io_ptr->my_blocked_q);
				//process interrupt
				Enqueue(intr, io_ptr->my_interrupt_q);
			}
		}
}
